<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <div class="createPost-main-container">
        <el-row>

          <el-col :span="24">

            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="140px" label="订单编号" class="postInfo-container-item">
                    <el-input v-model="postForm.order_id" auto-complete="off" size="mini" disabled/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="140px" label="影片名称" class="postInfo-container-item">
                    <el-input v-model="postForm.title" auto-complete="off" size="mini" disabled/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="140px" label="订单价格:" class="postInfo-container-item">
                    <el-input v-model="postForm.amount" auto-complete="off" size="mini" disabled/>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="140px" label="客户名称" class="postInfo-container-item">
                    <el-input v-model="postForm.nickname" auto-complete="off" size="mini" disabled/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="140px" label="订单状态" class="postInfo-container-item">
                    <el-input v-model="postForm.order_status_desc" auto-complete="off" size="mini" disabled/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="140px" label="订单项目经理" class="postInfo-container-item">
                    <el-input v-model="postForm.manager_nickname" auto-complete="off" size="mini" disabled/>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="140px" label="订单制作方" class="postInfo-container-item">
                    <el-input v-model="postForm.team_name" auto-complete="off" size="mini" disabled/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="140px" label="影片时长" class="postInfo-container-item">
                    <el-input v-model="postForm.video_duration" auto-complete="off" size="mini" disabled/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="140px" label="拍摄天数" class="postInfo-container-item">
                    <el-input v-model="postForm.shoot_day" :min="1" :max="1000" size="mini" disabled/>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="140px" label="视频类型" class="postInfo-container-item">
                    <el-input v-model="postForm.video_type_name" placeholder="请输入" disabled/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="140px" label="发票税号" class="postInfo-container-item">
                    <el-input v-model="postForm.tax_code" size="mini" disabled/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="140px" label="发票单位" class="postInfo-container-item">
                    <el-input v-model="postForm.tax_unit" size="mini" disabled/>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="140px" label="主拍城市" class="postInfo-container-item">
                    <el-input v-model="postForm.city" placeholder="请输入" disabled/>
                  </el-form-item>
                </el-col>
              </el-row>

            </div>
          </el-col>
        </el-row>
        <el-form-item label-width="140px" label="元素列表">
          <table>
            <tr v-for="(item, index) in eleComponents" :key="index">
              <td>
                <template>
                  <el-select v-model="postForm.order_elements[index]['id']" filterable size="mini" placeholder="请选择" disabled>
                    <el-option
                      v-for="item in elementOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                  <el-input-number v-model="postForm.order_elements[index]['num']" :min="1" :max="10000" size="mini" disabled/>
                </template>
              </td>
              <td>
                <!-- <el-button type="danger" size="mini" icon="el-icon-delete" @click="delElement(index)"/> -->
              </td>
            </tr>
          </table>
          <!-- <el-button type="success" size="mini" @click="addElements()">增加元素</el-button> -->
        </el-form-item>
      </div>
    </el-form>

  </div>
</template>

<script>
import Vue from 'vue'
import Upload from '@/components/Upload/singleImage3'
import { getToken } from '@/utils/auth'
import Sticky from '@/components/Sticky' // 粘性header组件
import { fetchAllElements } from '@/api/elements'
import { fetchAllTags } from '@/api/tag'
import { fetchAllTeams } from '@/api/team'
import { fetchAllVideoTypes } from '@/api/videotype'
import { createVideo, updateVideo } from '@/api/video'
import { fetchOrder } from '@/api/orders'

const defaultForm = {
  id: undefined,
  state: 0,
  show_order: '',
  title: '',
  sub_title: '',
  content: '',
  image_file: '',
  url: '',
  ini_play_time: 0,
  desc: '',
  sub_desc: '',
  user_price: 0.00,
  video_source: '',
  detail: [],
  detail_url: [],
  ini_sold_num: 0,
  price_unit: '',
  tips: '',
  shoot_day: 1,
  duration: 1,
  team_id: '',
  video_type_id: '',
  extra_price: 0,
  tax_unit: '',
  tax_code: '',
  elements: [{ elementId: '', num: 0 }],
  tags: [{ tagId: '' }]
}

export default {
  name: 'OrderDetail',
  components: { Upload, Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    currentId: {
      type: Number,
      default: undefined
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      postForm: Object.assign({}, defaultForm),
      eleComponents: [0],
      tagComponents: [0],
      tagOptions: [],
      elementOptions: [],
      teamOptions: [],
      videoTypeOptions: [],
      dialogImageUrl: '',
      dialogVisible: false,
      stateOptions: [{ 'label': '有效', 'value': 0 }, { 'label': '无效', 'value': 1 }],
      videoSourceOptions: [{ value: 1, label: '单品' }, { value: 2, label: '样片' }],
      loading: false,
      rules: {
        name: [{ required: true, trigger: 'blur', validator: validateRequire }]
      },
      tempRoute: {}
    }
  },
  computed: {
    authHeader() {
      const token = getToken()
      return { 'Authorization': token }
    },
    lang() {
      return this.$store.getters.language
    }
  },
  watch: {
    currentId: {
      handler: function(val, oldval) {
        // this.clearPostForm()
        console.log(val, oldval)
        if (val !== undefined && val > 0) {
          this.fetchData(val)
        }
      },
      deep: true
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.currentId
      this.fetchData(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }
    this.fetchTags()
    this.fetchTeams()
    this.fetchElements()
    this.fetchVideoTypes()
  },
  methods: {
    clearPostForm() {
      this.postForm = Object.assign({}, defaultForm)
    },
    handleDetailImgSuccess(response) {
      console.log(response)
      this.postForm.detail[this.postForm.detail.length] = response.data.url
    },
    handleRemove(file, fileList) {
      this.fileChange(fileList)
    },
    fileChange(fileList) {
      const temp_detail = []
      const temp_detail_url = []
      if (fileList.length > 0) {
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].response) {
            if (fileList[i].response.code === 0) {
              temp_detail[temp_detail.length] = fileList[i].response.data
              temp_detail_url[temp_detail_url.length] = { url: fileList[i].response.data }
            }
          } else if (fileList[i].status && fileList[i].status === 'success') {
            temp_detail[temp_detail.length] = fileList[i].url
            temp_detail_url[temp_detail_url.length] = { url: fileList[i].url }
          }
        }
      }
      this.postForm.detail = temp_detail
      this.postForm.detail_url = temp_detail_url
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    addTag() {
      Vue.set(this.postForm.tags, this.postForm.tags.length, { tagId: '' })
      Vue.set(this.tagComponents, this.tagComponents.length, this.tagComponents[this.tagComponents.length - 1] + 1)
    },
    delTag(index) {
      this.postForm.tags.splice(index, 1)
      this.tagComponents.splice(index, 1)
    },
    addElements() {
      Vue.set(this.postForm.elements, this.postForm.elements.length, { elementId: '', num: 0 })
      Vue.set(this.eleComponents, this.eleComponents.length, this.eleComponents[this.eleComponents.length - 1] + 1)
    },
    delElement(index) {
      this.postForm.elements.splice(index, 1)
      this.eleComponents.splice(index, 1)
    },
    handleVideoSuccess(res, file) {
      this.postForm.url = res.data.url
    },
    beforeVideoUpload(file) {
      console.log(file)
    },
    fetchTags() {
      fetchAllTags().then(response => {
        const tags = response.data.data.tags
        const tmpArr = []
        tags.forEach(element => {
          tmpArr[tmpArr.length] = { label: element.name, value: element.id }
        })
        this.tagOptions = tmpArr
      })
    },
    fetchElements() {
      fetchAllElements().then(response => {
        this.elementOptions = response.data.data.elements
      })
    },
    fetchVideoTypes() {
      fetchAllVideoTypes().then(response => {
        this.videoTypeOptions = response.data.data.video_types
      })
    },
    fetchTeams() {
      fetchAllTeams().then(response => {
        this.teamOptions = response.data.data.teams
      })
    },
    fetchData(id) {
      fetchOrder(id).then(response => {
        this.postForm = response.data.data
        console.log(this.postForm)
        const elements = this.postForm.order_elements
        this.eleComponents = []
        for (let index = 0; index < elements.length; index++) {
          // Vue.set(this.postForm.elements, this.postForm.elements.length, { elementId: '', num: 0 })
          Vue.set(this.eleComponents, this.eleComponents.length, this.eleComponents[this.eleComponents.length - 1] + 1)
        }
        const tags = this.postForm.tags
        this.tagComponents = []
        for (let index = 0; index < tags.length; index++) {
          // Vue.set(this.postForm.tags, this.postForm.tags.length, { tagId: '' })
          Vue.set(this.tagComponents, this.tagComponents.length, this.tagComponents[this.tagComponents.length - 1] + 1)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    submitForm() {
      this.postForm.display_time = parseInt(this.display_time / 1000)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          let requestFunc = createVideo
          let msg = '商品创建成功'
          if (this.postForm.id !== undefined && this.postForm.id > 1) {
            requestFunc = updateVideo
            msg = '商品修改成功'
          }
          requestFunc(this.postForm).then(response => {
            const r = response.data
            console.log(r)
            if (r.code === 0) {
              this.$notify({
                title: '成功',
                message: msg,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$message({ message: r.msg, type: 'error' })
            }
          })
          this.loading = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/styles/mixin.scss";
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: -10px;
    top: 0px;
  }
}
</style>
